/**
 * Copyright (C) 2011-2012 Rustam Bogubaev
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 */
package com.google.code.myminimvc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.el.BeanELResolver;
import javax.el.ELContext;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.PageContext;

/**
 * Created by IntelliJ IDEA.
 * User: dev
 * Date: 8/6/11
 * Time: 12:55 AM
 */
public class ModelELResolver extends BeanELResolver {
    private final Logger logger = LoggerFactory.getLogger(ModelELResolver.class);
    private static final String BASE_NAME = "model";

    public ModelELResolver() {
        super(true);
    }

    @Override
    public Object getValue(ELContext context, Object base, Object property) {
        try {
            if (base != null) {
                return resolveProperty(context, base, property);
            } else {
                return resolveBase(context, property);
            }
        } catch (Exception e) {
            logger.warn(e.getMessage() + " due to " + e.getCause());
            return null;
        }
    }

    @Override
    public boolean isReadOnly(ELContext context, Object base, Object property) {
        return true;
    }

    private Object resolveProperty(ELContext context, Object base, Object property) {
        if (!(base instanceof Controller)) {
            return null;
        }

        Class<?> type = getType(context, base, property);

        if (type == null) {
            context.setPropertyResolved(true);
            return null;
        }

        return super.getValue(context, base, property);
    }

    private Object resolveBase(ELContext context, Object property) {
        if (BASE_NAME.equals(property)) {
            PageContext pageContext = (PageContext) context.getContext(JspContext.class);
            Object o = pageContext.getRequest().getAttribute(Application.KEY_REQUEST_MODEL_HOLDER);
            context.setPropertyResolved(true);

            return o;
        } else {
            return null;
        }
    }

    @Override
    public Class<?> getType(ELContext elContext, Object o, Object o1) {
        try {
            return super.getType(elContext, o, o1);
        } catch (Exception e) {
            logger.warn(e.getMessage() + " due to " + e.getCause());
            return null;
        }
    }
}
